package com.qingxin.sys.smslib;

import com.qingxin.sys.support.BaseThread;

/**
 * 短信发送线程类，从短信队列读取短信进行发送
 * @author Administrator
 *
 */
public class SmsOutDataThread extends BaseThread {
	
	//唯一实例
	private static SmsOutDataThread smsOutDataThread;
	
	/**
	 * 获取唯一实例
	 * @return
	 */
	public static SmsOutDataThread getInstance(){
		if(smsOutDataThread != null && smsOutDataThread.isRunning()){
			return smsOutDataThread;
		}
		smsOutDataThread = new SmsOutDataThread();
		return smsOutDataThread;
	}
	
	
	/**
	 * 线程是否运行中
	 * @return
	 */
	public static boolean isActive(){
		return smsOutDataThread != null && smsOutDataThread.isRunning();
	}
	
	
	private long prevTime;//上一次发送时间
	private long delayTime;//延时时间
	
	private final long interval = 6000;
	
	private SmsOutDataThread() {
	}
	
	
	@Override
	public void run() {
		running = true;
		while(running){
			try {
				SmsOutDataDeque.tryWait(delayTime);
				if(!isRunning()){
					continue;
				}
				long time = System.currentTimeMillis() - prevTime;
				if(time < interval){
					delayTime = interval - time;
					continue;
				}
				
				SmsData smsData = SmsOutDataDeque.poll();
				if(smsData == null){
					continue;
				}
				
				//发送
				//System.out.println(smsData);
				SmsFactory.send(smsData);
				
				prevTime = System.currentTimeMillis();
				delayTime = interval;
				
			} catch (Exception e) {
				e.printStackTrace();
				try {
					Thread.sleep(1000);
				} catch (Exception e2) {
				}
			}
		}
		smsOutDataThread = null;
		running = false;
		SmsOutDataDeque.clear();
	}
	
	
}
